/*
 * DictionaryActivity.java
 *
 * Copyright(c) 2010
 * Michael Kroez
 * kroez@studiorutton.de
 *
 * All rights reserved.
 *
 * $Id$
 * 
 */

package de.studiorutton.gerengdic.dictionary;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;

import de.studiorutton.colorschemes.Buttonizer;
import de.studiorutton.colorschemes.IColorSchemeMapper;
import de.studiorutton.gerengdic.AboutDialogs;
import de.studiorutton.gerengdic.Preferences;
import de.studiorutton.gerengdic.Prefs;
import de.studiorutton.gerengdic.R;
import de.studiorutton.gerengdic.databaseaccess.ContentAccess;
import de.studiorutton.gerengdic.dictionary.Dictionary;
import de.studiorutton.gerengdic.dictionary.DictionaryAdapter;
import de.studiorutton.gerengdic.history.DictionaryCommand;
import de.studiorutton.gerengdic.history.HistoryActivity;
import de.studiorutton.gerengdic.indexeddictionary.IndexedDictionaryActivity;
import de.studiorutton.gerengdic.library.LibraryException;
import de.studiorutton.gerengdic.update.UpdateDatabaseListActivity;
import de.studiorutton.thresholdedittext.ThresholdEditText;
import de.studiorutton.thresholdedittext.ThresholdTextChanged;

public class DictionaryActivity extends ListActivity implements
		IDictionaryView {
	private static final String TAG = "learningwords";

	private ThresholdEditText et;
	private Button b;
	private ProgressBar pb;
	private Button eb;
	private ListView lv;

	private static final int SEARCH_FRESH = 1;
	private static final int SEARCH_NO = 2;
	private static final int SEARCH_REFRESH = 3;

	public static boolean RESTART_SEARCH;

	Dictionary d;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// Log.d(TAG, "DictionaryActivity: starting onCreate");
		setContentView(R.layout.dictionary);
		getWindow().setFormat( PixelFormat.RGBA_8888);

	}

	@Override
	public void onStart() {
		super.onStart();
		// Log.d(TAG, "DictionaryActivity: starting onStart");
		et = (ThresholdEditText) findViewById(R.id.searchtext);
		b = (Button) findViewById(R.id.searchlanguage);
		pb = (ProgressBar) findViewById(R.id.searchprogress);
		eb = (Button) findViewById(R.id.erasebutton);
		lv = getListView();

		d = Dictionary.get();

		IColorSchemeMapper csmi = Prefs.getInstance().getColorSchemeMapper();
		LinearLayout ll = (LinearLayout) findViewById(R.id.dictionary);
		ll.setBackgroundColor(csmi.getBackgroundColor());

		RelativeLayout rl = (RelativeLayout) findViewById(R.id.searchparent);
		rl.setBackgroundDrawable(csmi.getTitleStyle().getSearchBackground());

		lv.setDivider(csmi.getListDividerDrawable());
		boolean eraseButtonInvisible = !Prefs.getInstance()
				.getEraseButtonEnabled();
		eb.setBackgroundDrawable( csmi.getTitleStyle().getButtons().getDrawable( Buttonizer.ERASE_DRAWABLE ));
		checkClearVisibility(eraseButtonInvisible);

		try {
			// if (isLaunching())
			d.init();
			d.setDictionaryView(this);
		} catch (Exception e) {
			showErrorDialog(e.getLocalizedMessage());
		}
	}

	@Override
	public void onResume() {
		super.onResume();
		// Log.d(TAG, "DictionaryActivity: starting onResume");
		int executeSearch = executeExtras();

		updateSearchEditText();
		updateProgressBar(d.isRunning());
		updateLanguageButton();
		updateClearButton();
		updateSearchList(true);

		if (RESTART_SEARCH)
			executeSearch = SEARCH_FRESH;

		if (executeSearch != SEARCH_NO)
			executeCommand(executeSearch);

	}

	@Override
	protected void onPause() {
		super.onPause();

		d.setDictionaryPosition(lv.getFirstVisiblePosition());

		if (isFinishing()) {
			Dictionary.release();
			d = null;
		}
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	@Override
	public Dialog onCreateDialog(int id) {
		AboutDialogs ad = new AboutDialogs(this);
		return ad.onCreateDialog(id);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.dictionarymenu, menu);
		return true;
	}

	private int executeExtras() {
		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			String searchString = extras
					.getString(DictionaryCommand.MY_SEARCH_STRING_KEY);
			d.setSearchString(searchString);

			int searchLang = extras.getInt(DictionaryCommand.MY_SEARCH_LANG_KEY);
			d.setLanguage(searchLang);
			
			if (d.equalsToLastSearchString(searchString))
				return SEARCH_REFRESH;
			else
				return SEARCH_FRESH;
		}
		return SEARCH_NO;
	}

	private void executeCommand(int executeSearch) {
		RESTART_SEARCH = false;
		if (executeSearch == SEARCH_FRESH) {
			try {
				d.startDictionarySearch();
			} catch (LibraryException e) {
				showErrorDialog(e.getLocalizedMessage());
			}
		}

		updateSearchEditText();
		updateLanguageButton();
		updateSearchList(false);
		updateProgressBar(d.isRunning());
	}

	private void checkClearVisibility(boolean eraseButtonInvisible) {
		if (eraseButtonInvisible) {
			eb.setVisibility(View.INVISIBLE);
			RelativeLayout.LayoutParams params = (android.widget.RelativeLayout.LayoutParams) b
					.getLayoutParams();
			params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
			b.setLayoutParams(params);
		}
	}

	public void updateSearchEditText() {
		et.setCallbackDisabled( true );
		et.setText(d.getSearchString());
		et.setCallbackDisabled( false );
//		et.addTextChangedListener(mTextWatcher);
		et.setOnThresholdTextChanged( mThresholdTextChanged );
		et.setThreshold( 500 );
	}

	public void updateLanguageButton() {
		b.setOnClickListener(mlButtonListener);
		boolean color = Prefs.getInstance().getLanguageButtonColor();
		IColorSchemeMapper csmi = Prefs.getInstance().getColorSchemeMapper();
		int language = d.getLanguage();
		if (language == ContentAccess.LANGUAGE_BOTH) {
			b.setBackgroundDrawable(csmi.getTitleStyle().getButtons().getDrawable(
					Buttonizer.GERUK_DRAWABLE, color));
		} else if (language == ContentAccess.LANGUAGE_LEFT) {
			b.setBackgroundDrawable(csmi.getTitleStyle().getButtons().getDrawable(
					Buttonizer.GER_DRAWABLE, color));
		} else if (language == ContentAccess.LANGUAGE_RIGHT) {
			b.setBackgroundDrawable(csmi.getTitleStyle().getButtons().getDrawable(
					Buttonizer.UK_DRAWABLE, color));
		} else
			b.setText("???");
	}

	public void updateProgressBar(boolean isRunning) {
		if (isRunning)
			pb.setVisibility(View.VISIBLE);
		else
			pb.setVisibility(View.INVISIBLE);
	}

	public void updateSearchList(boolean setSelectionFromTop) {
		DictionaryAdapter da = d.getDictionaryAdapter();
		setListAdapter(da);
		if (setSelectionFromTop)
			lv.setSelection(d.getDictionaryPosition());
	}

	private void updateClearButton() {
		eb.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				d.setSearchString("");
				d.cancelDictionarySearch();
				d.clear();
				updateSearchEditText();
			}
		});
	}

	public void showErrorDialog(String msg) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(getResources().getString(R.string.error_occurred))
				.setMessage(msg)
				.setCancelable(false)
				.setPositiveButton(getResources().getString(R.string.okay),
						new android.content.DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
							}
						});
		AlertDialog alert = builder.create();
		alert.show();
	}

	public Context getContext() {
		return this;
	}

	private TextWatcher mTextWatcher = new TextWatcher() {

		public void afterTextChanged(Editable arg0) {
			// Log.d(TAG, "TextWatcher: afterTextChanged: '" + arg0.toString()
			// + "'");
			StringBuilder searchString = new StringBuilder(arg0.toString());
			if (d.equalsToLastSearchString(searchString.toString())) {
				Log.d(TAG, "TextWatcher: exit");
				return;
			}

//			Log.d(TAG, "TextWatcher: starting new search");
			d.setSearchString(searchString.toString());
			try {
				d.startDictionarySearch();
			} catch (Exception e) {
				showErrorDialog(e.getLocalizedMessage());
			}
		}

		public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
				int arg3) {
			// Log.d(TAG, "TextWatcher: beforeTextChanged");
		}

		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			// Log.d(TAG, "TextWatcher: onTextChanged: '" + s + "'");

		}
	};
	
	private ThresholdTextChanged mThresholdTextChanged = new ThresholdTextChanged() {

        public void onThresholdTextChanged(Editable text) {
        	if ( text == null )
        		return;
        	StringBuilder searchString = new StringBuilder(text.toString());
			if (d.equalsToLastSearchString(searchString.toString())) {
				Log.d(TAG, "TextWatcher: exit");
				return;
			}

//			Log.d(TAG, "TextWatcher: starting new search");
			d.setSearchString(searchString.toString());
			try {
				d.startDictionarySearch();
			} catch (Exception e) {
				showErrorDialog(e.getLocalizedMessage());
			}
        }
	};

	private OnClickListener mlButtonListener = new OnClickListener() {
		public void onClick(View arg0) {
			int language = d.getLanguage();
			if (language == ContentAccess.LANGUAGE_BOTH)
				language = ContentAccess.LANGUAGE_LEFT;
			else if (language == ContentAccess.LANGUAGE_LEFT)
				language = ContentAccess.LANGUAGE_RIGHT;
			else
				language = ContentAccess.LANGUAGE_BOTH;

			d.setLanguage(language);
			updateLanguageButton();
			try {
				d.updateLanguage(DictionaryActivity.this);
			} catch (LibraryException e) {
				showErrorDialog(e.getLocalizedMessage());
			}
		}
	};

	public static final int DATABASE_UPDATE = 10;

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		Intent i;
		switch (item.getItemId()) {
		case R.id.menudictionary:
			i = new Intent(getApplicationContext(), DictionaryActivity.class);
			i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP );
			startActivity(i);
			return true;
		case R.id.menuindexeddictionary:
			i = new Intent(getApplicationContext(),
					IndexedDictionaryActivity.class);
			i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP );
			startActivity(i);
			return true;
		case R.id.searchhistory:
			i = new Intent(getApplicationContext(), HistoryActivity.class);
			startActivity(i);
			return true;
		case R.id.menuupdatedatabase:
			i = new Intent(getApplicationContext(),
					UpdateDatabaseListActivity.class);
			startActivityForResult(i, DATABASE_UPDATE);
			return true;
		case R.id.preferences:
			i = new Intent(getApplicationContext(), Preferences.class);
			startActivity(i);
			return true;
		case R.id.about:
			showDialog(AboutDialogs.ABOUT_DIALOG_MAIN);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}
}
